﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BrightIdeasSoftware;
using Dataweb.NShape;
using Dataweb.NShape.Controllers;
using Dataweb.NShape.GeneralShapes;
using Dataweb.NShape.SoftwareArchitectureShapes;
using DBCodeBuilder.CodeGeneration.Domain;
using DBCodeBuilder.Core;
using DBCodeBuilder.Core.Classes;
using DBCodeBuilder.Core.Enum;
using DBCodeBuilder.Core.Factories;
using DBCodeBuilder.Core.Interfaces;
using DBCodeBuilder.Core.Models;
using DBCodeBuilder.UI;
using HSystem.Data;
using Label = Dataweb.NShape.GeneralShapes.Label;

namespace DBCodeBuilder
{
    public partial class Main_Designer : Form
    {
        private const string ExpectedConfigVersion = "2.0";
        private Diagram diagramTab;
        private List<TableModel> tables;
        private GraphicHelper GraphicHelper;
        private bool showCodeGenErrors = true;
        private string TablesCode { get; set; }
        private string ProceduresCode { get; set; }
        private string CodeGenLog { get; set; }
        private string LastLoadedConfig { get; set; }

        public Main_Designer()
        {
            InitializeComponent();
            splDesignerToolbox.Panel2Collapsed = true;
            saveConfigFileDialog.InitialDirectory = SessionInfo.ConfigDirPath;
            openConfigFileDialog.InitialDirectory = SessionInfo.ConfigDirPath;

            syntaxDocument.SyntaxFile = "SyntaxFiles\\CSharp.syn";
        }

        #region DB Load

        private void RefreshTablesMetadata()
        {
            var toGatherFromDB = tables.Where(table => table.MetaData == null).ToList();

            Parallel.ForEach(toGatherFromDB, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
                table =>
                {
                    if (table.ObjectType == DbObjectType.Table)
                        table.MetaData = DbMetadata.GetTable(table.Owner + "." + table.Name, "app", true, true, true, false, true);
                    else
                        table.MetaData = DbMetadata.GetView(table.Owner + "." + table.Name, "app");
                });
        }

        private void RefreshTableMetadata(TableModel table)
        {
            if (table.ObjectType == DbObjectType.Table)
                table.MetaData = DbMetadata.GetTable(table.Owner + "." + table.Name, "app", true, true, true, false, true);
            else
                table.MetaData = DbMetadata.GetView(table.Owner + "." + table.Name, "app");
        }

        #endregion

        #region Events

        private void Main_Designer_Load(object sender, EventArgs e)
        {
            WriteConfigLabel();

            project.AddLibraryByName("Dataweb.NShape.GeneralShapes", false);
            project.AddLibraryByName("Dataweb.NShape.SoftwareArchitectureShapes", false);
            project.Name = "DesigningProject";
            project.Create();

            toolBoxAdapter.ToolSetController.Clear();
            toolBoxAdapter.ToolSetController.AddTool(new SelectionTool(), true);
            toolBoxAdapter.ToolSetController.SelectedTool = toolBoxAdapter.ToolSetController.DefaultTool;

            diagramTab = new Diagram(string.Format("Diagramma Tabelle"))
            {
                Width = 6000,
                Height = 6000,
                BackgroundGradientColor = Color.WhiteSmoke
            };

            ColorStyle colorStyleTableBase = new ColorStyle("colorStyleTableBase", Color.CornflowerBlue);
            ColorStyle colorStyleTableGradient = new ColorStyle("colorStyleTableGradient", Color.LightSkyBlue);
            ColorStyle colorStyleViewBase = new ColorStyle("colorStyleViewBase", Color.SeaGreen);
            ColorStyle colorStyleViewGradient = new ColorStyle("colorStyleViewGradient", Color.LightGreen);
            FillStyle fillStyleTable = new FillStyle("fillStyleTable", colorStyleTableBase, colorStyleTableGradient) { FillMode = FillMode.Gradient };
            FillStyle fillStyleView = new FillStyle("fillStyleView", colorStyleViewBase, colorStyleViewGradient) { FillMode = FillMode.Gradient };
            ColorStyle colorStyleBlack = new ColorStyle("colorStyleBlack", Color.Black);
            ColorStyle colorStyleDarkRed = new ColorStyle("colorStyleDarkRed", Color.DarkRed);
            CharacterStyle charStyleLabel = new CharacterStyle("LabelStyle", 16, colorStyleBlack);
            CharacterStyle charStyleLabelNotGenerated = new CharacterStyle("LabelStyleNotGen", 16, colorStyleDarkRed);
            LineStyle relGenerated = new LineStyle("RelGenerated", 2, colorStyleBlack);
            LineStyle relNotGenerated = new LineStyle("RelNotGenerated", 2, colorStyleDarkRed);

            AddStyle(colorStyleTableBase);
            AddStyle(colorStyleTableGradient);
            AddStyle(colorStyleViewBase);
            AddStyle(colorStyleViewGradient);
            AddStyle(fillStyleTable);
            AddStyle(fillStyleView);
            AddStyle(colorStyleBlack);
            AddStyle(colorStyleDarkRed);
            AddStyle(charStyleLabel);
            AddStyle(charStyleLabelNotGenerated);
            AddStyle(relGenerated);
            AddStyle(relNotGenerated);

            GraphicHelper = new GraphicHelper(cachedRepository, project, diagramTab, dspTables);
            GraphicHelper.SetDefaultShapes(project.ShapeTypes["Entity"], project.ShapeTypes["RectangularLine"], project.ShapeTypes["Label"]);
            InitBoard();
        }

        private void AddStyle(IStyle style)
        {
            project.Design.AddStyle(style);
            project.Repository.Insert(project.Design, style);
        }

        private void displayer_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void displayer_DragDrop(object sender, DragEventArgs e)
        {
            DispatchAndDraw(e);
        }

        private void dspTables_ShapesRemoved(object sender, DiagramPresenterShapesEventArgs e)
        {
            List<EntitySymbol> removed = e.Shapes.Where(shape => shape.GetType() == typeof(EntitySymbol)).Cast<EntitySymbol>().ToList();

            foreach (var tab in removed)
            {
                var tabl = tables.Single(t => t.Name == (string)tab.Tag);
                tabl.ShapePlacementInfo = null;
                tables.Remove(tabl);
            }

            GraphicHelper.RemoveLinkedShapes(removed);
            objectSelector.RefreshObjects();
        }

        private void splBtnSalva_Click(object sender, EventArgs e)
        {
            Save(true, true);
        }

        private void tuttoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save(true, true);
        }

        private void domainToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save(true, false);
        }

        private void mappingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save(false, true);
        }

        private void sPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Save(false, false);
        }

        private void btnSplit_CheckedChanged(object sender, EventArgs e)
        {
            splDesignerToolbox.Panel2Collapsed = !btnSplit.Checked;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshAll();
        }

        private void btnOpenSaveFolder_Click(object sender, EventArgs e)
        {
            Process.Start(SessionInfo.Instance.SaveFolder);
        }

        private void nuovoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(LastLoadedConfig))
            {
                if (MessageBox.Show("Are you sure you want to start anew discarding the changes to the loaded configuration?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                    return;
            }
            InitBoard();
            objectSelector.Reset();
        }

        private void versioneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Info().ShowDialog();
        }

        private void salvaConfigurazioneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveConfigFileDialog.FileName = String.IsNullOrEmpty(LastLoadedConfig) ? "Config.config" : LastLoadedConfig;

            if (saveConfigFileDialog.ShowDialog() != DialogResult.OK)
                return;

            ConfigSetup config = new ConfigSetup
            {
                MappingNamespace = txtMappingNamespace.Text,
                ModelNamespace = txtDomainNamespace.Text,
                tables = tables,
                Owner = objectSelector.SelectedOwner,
                SelectedObjectType = objectSelector.SelectedObjectType,
                Version = ExpectedConfigVersion
            };
            config.Save(saveConfigFileDialog.FileName);

            MessageBox.Show("Configuration save succesfull.", "Configuration saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void caricaConfigurazioneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (openConfigFileDialog.ShowDialog() != DialogResult.OK)
                return;
            Cursor = Cursors.WaitCursor;

            ConfigSetup configs = ConfigSetup.LoadConfig(openConfigFileDialog.FileName);
            if (configs.Version != ExpectedConfigVersion)
            {
                MessageBox.Show("Not supported configuration version", "Error loading configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = DefaultCursor;
                return;
            }
            LastLoadedConfig = openConfigFileDialog.SafeFileName;

            tables.Clear();
            tables.AddRange(configs.tables);

            List<string> exceptions;
            if (!objectSelector.LoadByConfig(configs, out exceptions))
            {
                Cursor = DefaultCursor;
                return;
            }

            if (exceptions.Count > 0)
            {
                string aggregate = exceptions.Aggregate("", (current, ex) => current + (ex + Environment.NewLine));
                MessageBox.Show("The state of some of the loaded objects have been changed:\n" + aggregate, "Objects changed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            txtDomainNamespace.Text = configs.ModelNamespace;
            txtMappingNamespace.Text = configs.MappingNamespace;

            RefreshAll();

            Cursor = DefaultCursor;
        }

        private void configurazioneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new Config().ShowDialog();

            WriteConfigLabel();
        }

        private void esciToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(LastLoadedConfig))
                if (MessageBox.Show("Are you sure you want to exit discarding the changes to the loaded configuration?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                    return;

            Close();
        }

        private void objectSelector_OnSchemaChanged(object sender, EventArgs e)
        {
            InitBoard();
        }

        private void cachedRepository_ShapesUpdated(object sender, RepositoryShapesEventArgs e)
        {
            var shapes = GraphicHelper.GetOnlyEntities(e.Shapes.ToList());
            if (shapes.Count == 0)
                return;

            if (shapes.Count > 1)
            {
                foreach (var shape in shapes)
                {
                    var refModel = tables.Single(t => t.Name == (string)shape.Tag);
                    refModel.ShapePlacementInfo.Location = new Point(shape.X, shape.Y);
                    refModel.ShapePlacementInfo.Size = new Size(shape.Width, shape.Height);
                }
                return;
            }

            var element = (EntitySymbol)e.Shapes.ElementAt(0);
            var newTitle = element.Text;
            var referencedModel = tables.Single(t => t.Name == (string)element.Tag);
            referencedModel.ShapePlacementInfo.Location = new Point(element.X, element.Y);
            referencedModel.ShapePlacementInfo.Size = new Size(element.Width, element.Height);

            var logicRelList = tables.SelectMany(t => t.References).Where(t => t.OriginalTable == element.Tag.ToString() || t.RefTable == element.Tag.ToString()).ToList();
            GraphicHelper.UpdateRelationshipLabels(logicRelList, tables);

            if (referencedModel.Name == newTitle)
                return;

            referencedModel.UserMapping.ClassName = newTitle;
            RefreshCode();
        }

        private void map_Props1_OnSave(object sender, EventArgs e)
        {
            if (sender.GetType() == typeof(TableModel))
            {
                var newModel = ((TableModel)sender);
                GraphicHelper.UpdateTableShape(newModel);
            }
            if (sender.GetType() == typeof(DbRelationship))
            {
                var newRel = ((DbRelationship)sender);
                GraphicHelper.UpdateRelationshipLabel(newRel, tables);
                GraphicHelper.UpdateRelationshipLine(newRel);
            }

            RefreshCode();
        }

        private void dspTables_ShapesSelected(object sender, EventArgs e)
        {
            if (dspTables.SelectedShapes.Count > 1)
            {
                var shapesToSelect = GraphicHelper.GetOnlyEntities(dspTables.SelectedShapes.ToList());

                if (shapesToSelect.Count == dspTables.SelectedShapes.Count)
                    return;

                dspTables.UnselectAll();
                dspTables.SelectShapes(shapesToSelect, true);
            }

            if (dspTables.SelectedShapes.Count == 0)
            {
                map_Props1.Visible = false;
                RefreshCode();
            }
            else
            {
                var selectedShape = dspTables.SelectedShapes.ElementAt(0);

                if (selectedShape.GetType() == typeof(EntitySymbol) && ModifierKeys == Keys.Control)
                {
                    List<Shape> linkedShapes = GraphicHelper.GetLinkedShapes((EntitySymbol)selectedShape);

                    dspTables.ShapesSelected -= dspTables_ShapesSelected;
                    dspTables.SelectShapes(linkedShapes, true);
                    dspTables.ShapesSelected += dspTables_ShapesSelected;
                }

                if (selectedShape.GetType() == typeof(EntitySymbol))
                {
                    var selected = tables.Single(t => t.Name == (string)dspTables.SelectedShapes.ElementAt(0).Tag);
                    map_Props1.Init(selected);
                    ShowCodeFor(selected);
                }
                else if (selectedShape.GetType() == typeof(RectangularLine))
                {
                    var line = (RectangularLine)selectedShape;
                    var rel = GraphicHelper.GetDBRelByRelationshipLine(line, tables);

                    map_Props1.Init(rel);
                }
                else if (selectedShape.GetType() == typeof(Label))
                {
                    var matchingShape = GraphicHelper.GetRelationshipByLabel((Label)selectedShape);
                    if (matchingShape == null)
                    {
                        dspTables.UnselectShape(selectedShape);
                        return;
                    }

                    dspTables.ShapesSelected -= dspTables_ShapesSelected;
                    dspTables.SelectShape(matchingShape, true);
                    dspTables.ShapesSelected += dspTables_ShapesSelected;

                    var rel = GraphicHelper.GetDBRelByRelationshipLine((RectangularLine)matchingShape, tables);
                    map_Props1.Init(rel);
                }
            }
        }

        private void sel_OnSelected(object sender, EventArgs e)
        {
            objectSelector.SelectObjectsByName((List<string>)sender);
        }

        private void Main_Designer_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4)
                tbcToolbox.SelectTab(tabMapProp);
            if (e.KeyCode == Keys.F7)
                tbcToolbox.SelectTab(tabCode);
            if (e.KeyCode == Keys.S && ModifierKeys == Keys.Control)
                salvaConfigurazioneToolStripMenuItem_Click(this, null);
            if (e.KeyCode == Keys.O && ModifierKeys == Keys.Control)
                caricaConfigurazioneToolStripMenuItem_Click(this, null);
            if (e.KeyCode == Keys.L && ModifierKeys == (Keys.Control | Keys.Shift))
                GraphicHelper.PopupLayouter(this);
        }

        private void dspTables_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Z && e.Modifiers == Keys.Control)
                e.Handled = true;
        }

        #endregion

        #region Code Gen

        private void GenerateTablesCode()
        {
            IMappingGenerator mapGen = MapGeneratorFactory.GetMapGenerator(SessionInfo.Instance.OrmCodeGeneration);
            ModelContainer.DrawingTableModels = tables;

            TablesCode = "//**************************************TABLES/VIEWS**************************************\n\n\n";
            foreach (TableModel tab in tables)
            {
                TablesCode += String.Format("//***{0}.{1}***\n", tab.Owner, tab.Name);
                mapGen.Generate(tab, SessionInfo.Instance.MapGenSettings);
                TablesCode += mapGen.Code + "\n" + mapGen.CodeMapping + "\n\n";

                tab.GeneratedClass = mapGen.Code;
                tab.GeneratedMapping = mapGen.CodeMapping;
                tab.GeneratedClassName = mapGen.GeneratedClassName;
                CodeGenLog += mapGen.LogMessage;
            }

            if (!String.IsNullOrEmpty(CodeGenLog) && showCodeGenErrors)
            {
                MessageBox.Show(CodeGenLog, "One or more errors occured during code generation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                showCodeGenErrors = false;
            }
            CodeGenLog = String.Empty;
        }

        #endregion

        #region Draw

        private void DispatchAndDraw(DragEventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            List<IDbObjectModel> data = ((OLVDataObject)e.Data).ModelObjects.Cast<IDbObjectModel>().ToList();
            List<IDbObjectModel> tabs, views;
            Utility.DispatchObjects(((OLVDataObject)e.Data).ModelObjects.Cast<IDbObjectModel>().ToList(), out tabs, out views);

            objectSelector.RemoveObjects(data);

            bool tablesAdded = tabs.Count > 0 || views.Count > 0;

            if (tabs.Count > 0)
                tables.AddRange(tabs.Cast<TableModel>());
            if (views.Count > 0)
            {
                var vws = views.Select(t => ((ViewModel)t).TableRepresentation).ToList();
                tables.AddRange(vws);
                tabs.AddRange(vws);
            }

            TablesCode = ProceduresCode = String.Empty;

            var dropPoint = GetDropPoint(e);

            if (tablesAdded)
                TableDrawing(tabs, dropPoint);

            syntaxDocument.Text = (TablesCode + ProceduresCode).TrimEnd(Environment.NewLine.ToCharArray());
            Cursor = DefaultCursor;
        }

        private void TableDrawing(List<IDbObjectModel> tabs, Point dropPoint)
        {
            bool hasToUpdateRelationships = tables.Count == tabs.Count;
            if (tabs.Count == 1)
            {
                bool hasDiag = GraphicHelper.TableDiagramInRepositroy;
                var element = (TableModel)tabs.ElementAt(0);
                RefreshTableMetadata(element);
                GraphicHelper.DrawTable(element, hasDiag ? dropPoint.X : (int?)null, hasDiag ? dropPoint.Y : (int?)null, hasDiag);
                if (element.ObjectType == DbObjectType.Table)
                    GraphicHelper.UpdateTableRelationships(tables);
                GraphicHelper.AssignTableDiagram(tables.Count == 1);
                GenerateTablesCode();
            }
            else
            {
                GraphicHelper.CleanTableDrawspace();
                RefreshTablesMetadata();

                if (tables.Count == tabs.Count)
                    DrawTables(null, null, true);
                else
                    DrawTables(dropPoint.X, dropPoint.Y);

                GenerateTablesCode();
            }

            GraphicHelper.AssignTableRepositoryIfNecessary();

            if (hasToUpdateRelationships)
                GraphicHelper.UpdateRelationshipLabels(tables.SelectMany(t => t.References).ToList(), tables);
        }

        private Point GetDropPoint(DragEventArgs e)
        {
            int dx, dy;
            var ptc = dspTables.PointToClient(new Point(e.X, e.Y));
            dspTables.ControlToDiagram(ptc.X, ptc.Y, out dx, out dy);
            return new Point(dx, dy);
        }

        private void DrawTables(int? X = null, int? Y = null, bool performLayout = false)
        {
            pnlShowSave.Visible = false;
            GraphicHelper.DrawTables(tables, X, Y);

            if (performLayout)
                GraphicHelper.PerformTableLayouting(tables);

            GraphicHelper.AssignTableDiagram(true);
        }

        private void WriteConfigLabel()
        {
            lblOrm.Text = SessionInfo.Instance.OrmCodeGeneration.ToString();
        }

        #endregion

        #region Cleanup

        private void RefreshAll()
        {
            GraphicHelper.CleanTableDrawspace();

            TablesCode = String.Empty;
            ProceduresCode = String.Empty;
            showCodeGenErrors = true;

            foreach (TableModel tab in tables)
            {
                tab.GeneratedClass = String.Empty;
                tab.GeneratedClassName = String.Empty;
                tab.GeneratedMapping = String.Empty;
                tab.MetaData = null;
            }

            if (tables.Count > 0)
            {
                RefreshTablesMetadata();
                DrawTables();
                GenerateTablesCode();

                GraphicHelper.AssignTableRepositoryIfNecessary();
            }

            syntaxDocument.Text = (TablesCode + ProceduresCode).TrimEnd(Environment.NewLine.ToCharArray());
        }

        private void RefreshCode()
        {
            if (tables.Count > 0)
                GenerateTablesCode();

            syntaxDocument.Text = (TablesCode + ProceduresCode).TrimEnd(Environment.NewLine.ToCharArray());
        }

        private void ShowCodeFor(IDbObjectModel model)
        {
            switch (model.ObjectType)
            {
                case DbObjectType.Table:
                case DbObjectType.View:
                    var mdCast = (TableModel)model;
                    syntaxDocument.Text = String.Format("{0}\r\n\r\n{1}", mdCast.GeneratedClass, mdCast.GeneratedMapping).TrimEnd(Environment.NewLine.ToCharArray());
                    break;
            }
        }

        private void InitBoard()
        {
            tables = new List<TableModel>();

            objectSelector.tables = tables;

            GraphicHelper.CleanTableDrawspace();
            txtDomainNamespace.Text = "";
            txtMappingNamespace.Text = "";
            syntaxDocument.Text = "";
            pnlShowSave.Visible = false;
        }

        #endregion

        #region Code Save

        private void Save(bool saveDomain, bool saveMapping)
        {
            IMappingGenerator mapGen = MapGeneratorFactory.GetMapGenerator(SessionInfo.Instance.OrmCodeGeneration);

            string allDomainFilePath = SessionInfo.Instance.SaveFolder + "\\AllDomain.cs";
            string allMappingFilePath = SessionInfo.Instance.SaveFolder + "\\AllMapping.cs";
            string allCodeFilePath = SessionInfo.Instance.SaveFolder + "\\AllCode.cs";

            if (!Directory.Exists(SessionInfo.Instance.SaveFolder))
                Directory.CreateDirectory(SessionInfo.Instance.SaveFolder);

            if (File.Exists(allDomainFilePath) && SessionInfo.Instance.SaveAction == SaveAction.Overwrite)
                File.WriteAllText(allDomainFilePath, "");

            if (File.Exists(allMappingFilePath) && SessionInfo.Instance.SaveAction == SaveAction.Overwrite)
                File.WriteAllText(allMappingFilePath, "");

            if (File.Exists(allCodeFilePath) && SessionInfo.Instance.SaveAction == SaveAction.Overwrite)
                File.WriteAllText(allCodeFilePath, "");

            StringBuilder domainBuidler = new StringBuilder();
            StringBuilder mappingBuilder = new StringBuilder();
            foreach (TableModel tab in tables)
            {
                if (SessionInfo.Instance.FileSaveMode == SaveMode.SingleFile)
                {
                    if (saveDomain)
                        domainBuidler.AppendLine(tab.GeneratedClass);
                    if (saveMapping)
                        mappingBuilder.AppendLine(tab.GeneratedMapping);
                }
                else
                {
                    if (saveDomain)
                    {
                        if (!String.IsNullOrEmpty(txtDomainNamespace.Text))
                            File.WriteAllText(SessionInfo.Instance.SaveFolder + "\\" + tab.GeneratedClassName + ".cs", String.Format(mapGen.GetFileStructure(tab, txtDomainNamespace.Text, CodeFileStructure.Domain), tab.GeneratedClass));
                        else
                            File.WriteAllText(SessionInfo.Instance.SaveFolder + "\\" + tab.GeneratedClassName + ".cs", tab.GeneratedClass);
                    }
                    if (saveMapping)
                    {
                        if (!String.IsNullOrEmpty(txtMappingNamespace.Text))
                            File.WriteAllText(SessionInfo.Instance.SaveFolder + "\\" + tab.GeneratedClassName + "Map.cs", String.Format(mapGen.GetFileStructure(tab, txtMappingNamespace.Text, CodeFileStructure.Mapping, txtDomainNamespace.Text), tab.GeneratedMapping));
                        else
                            File.WriteAllText(SessionInfo.Instance.SaveFolder + "\\" + tab.GeneratedClassName + "Map.cs", tab.GeneratedMapping);
                    }
                }
            }

            if (SessionInfo.Instance.FileSaveMode == SaveMode.SingleFile)
            {
                if (!String.IsNullOrEmpty(txtDomainNamespace.Text))
                    File.WriteAllText(allDomainFilePath, String.Format(mapGen.GetFileStructure(null, txtDomainNamespace.Text, CodeFileStructure.Domain), domainBuidler.ToString().TrimEnd(Environment.NewLine.ToCharArray())));
                else
                    File.WriteAllText(allDomainFilePath, domainBuidler.ToString().TrimEnd(Environment.NewLine.ToCharArray()));

                if (!String.IsNullOrEmpty(txtMappingNamespace.Text))
                    File.WriteAllText(allMappingFilePath, String.Format(mapGen.GetFileStructure(null, txtMappingNamespace.Text, CodeFileStructure.Mapping), mappingBuilder.ToString().TrimEnd(Environment.NewLine.ToCharArray())));
                else
                    File.WriteAllText(allMappingFilePath, mappingBuilder.ToString().TrimEnd(Environment.NewLine.ToCharArray()));
            }
            pnlShowSave.Visible = true;
        }
        #endregion
    }
}